package com.tanhua.sso.controller;


import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param , Device device) {
        /**
         * 1,得到手机号和验证码
         * 2.将号码和验证码传给service,进行存在判断
         * 3.有,返回用户状态和token值
         *    无,返回一个状态码
         */
        String phone = param.get("phone");
        String verificationCode = param.get("verificationCode");
        String data=userService.login(phone,verificationCode,device);
        System.out.println("data:"+data);

        if(data!=null){
            //返回json数据
            HashMap<String,Object> result  = new HashMap<>(2);
            String[] ss = StringUtils.split(data, '|');
            result.put("token",ss[0]);
            result.put("isNewUser",Boolean.valueOf(ss[1]));
            System.out.println(result);


            return ResponseEntity.ok(result);
        }
        //利用ErrorResult返回错误信息
        ErrorResult errorResult = ErrorResult.builder().errCode("100").errMessage("用户被冻结").build();
        return ResponseEntity.status(500).body(errorResult);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
